package cn.tedu.ivos.application.service.impl;

import cn.tedu.ivos.application.mapper.ApplicationMapper;
import cn.tedu.ivos.application.pojo.dto.ApplicationQuery;
import cn.tedu.ivos.application.pojo.dto.ApplicationSaveParam;
import cn.tedu.ivos.application.pojo.entity.Application;
import cn.tedu.ivos.application.pojo.vo.ApplicationVO;
import cn.tedu.ivos.application.service.ApplicationService;
import cn.tedu.ivos.audit.mapper.AuditMapper;
import cn.tedu.ivos.audit.pojo.vo.AuditVO;
import cn.tedu.ivos.audit.service.AuditService;
import cn.tedu.ivos.base.enums.ApplicationStatusEnum;
import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.entity.Vehicle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Transactional
@Slf4j
@Service
public class ApplicationServiceImpl implements ApplicationService {
    @Autowired
    ApplicationMapper applicationMapper;
    @Autowired
    AuditService auditService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    AuditMapper auditMapper;
    @Autowired
    VehicleMapper vehicleMapper;

    @Override
    public void saveApplication(ApplicationSaveParam applicationSaveParam) {
        log.debug("保存申请单业务，参数：{}",applicationSaveParam);
        Application application = new Application();
        BeanUtils.copyProperties(applicationSaveParam,application);
        //申请单初始状态为“已发起”10
        application.setStatus(ApplicationStatusEnum.PENDING.getCode());
        application.setCreateTime(new Date());
        /* 遇到的问题：新增申请单对应的审批单数据时，审批单数据没有此申请单id
        * 原因：执行insert方法的SQL时，没有把生成的自增主键值回填到application对象中
        * 解决方法：给此SQL上添加 useGeneratedKeys="true" keyProperty="id"
        * 效果：JDBC会为当前application对象自动生成自增主键，并将生成的主键赋值给当前application对象的id属性
        * */

        applicationMapper.insert(application);

        //在上方创建好申请单后,调用审批模块的方法
        //为此申请单创建对应的审批单数据
        auditService.insertAudit(application);
    }

    @Override
    public List<ApplicationVO> selectApplication(ApplicationQuery applicationQuery) {
        log.debug("查询申请单业务，参数：{}", applicationQuery);
        List<ApplicationVO> list = applicationMapper.selectApplication(applicationQuery);
        //依次取出每一个申请单VO，为它补全对应的审批人数据
        for(int i=0;i<list.size();i++){
            ApplicationVO applicationVO =list.get(i);
            //处理当前的申请单VO，给它补全审批人字段的值
            assignAuditUserList(applicationVO);
        }
        return list;
    }
    /* 本方法用于给当前传入的申请单VO的审批人数据赋值，并不会生成新的申请单VO
    * 审批人id集合List<long> auditUserList =>[106,103]
    * 审批人姓名字符串String auditUsernameList;=>"moly,tom"
    * */
    private void assignAuditUserList(ApplicationVO applicationVO){
        //1.准备空集合，分别用来保存此申请单对应的审批人id与姓名
        List<Long> auditUserIdList = new ArrayList<>();
        List<String> auditUsernameList = new ArrayList<>();
        //2.根据传入的申请单对象，获取id，再查出所有的审批单
        List<AuditVO> auditVOList =
                auditService.selectAuditByApplicationId(applicationVO.getId());
        //3.依次遍历取出每一个审批单对象
        for(int i = 0;i < auditVOList.size(); i++){
            AuditVO auditVO =auditVOList.get(i);
            //4.获取当前遍历到的审批单中的审批人数据
            Long id = auditVO.getAuditUserId();
            auditUserIdList.add(id);
            //5.根据刚刚取出来的审批人id查出此人姓名，并装入上方
            UserVO userVO = userMapper.selectById(id);
            auditUsernameList.add(userVO.getUsername());
        }
        //6.准备一个拼接工具,帮我们将多个审批人姓名连成一个字符串
        StringJoiner stringJoiner = new StringJoiner(",");
        for(String username : auditUsernameList){
            stringJoiner.add(username);
        }
        //7.将拼接好的审批人姓名字符串赋值给方法形参ApplicationVO
        applicationVO.setAuditUsernameList(stringJoiner.toString());
        //8.将准备好的审批人id集合赋值给方法形参ApplicationVO
        applicationVO.setAuditUserIdList(auditUserIdList);
    }

    @Override
    public void cancel(Long id) {
        log.debug("撤销申请单业务，参数：{}",id);
        Application application = new Application();
        application.setId(id);
        application.setStatus(ApplicationStatusEnum.CANCEL.getCode());
        application.setUpdateTime(new Date());
        applicationMapper.update(application);
        //还需要删除此申请单下对应的所有审批单数据
        auditMapper.deleteByApplicationId(id);
    }

    @Override
    public void distribute(Long applicationId, Long vehicleId) {
        log.debug("分配车辆业务，参数：{}，{}",applicationId,vehicleId);
        Application application = new Application();
        application.setId(applicationId);
        application.setVehicleId(vehicleId);
        application.setStatus(ApplicationStatusEnum.ALLOCATION.getCode());
        application.setUpdateTime(new Date());
        applicationMapper.update(application);

        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setStatus("2");//车辆状态改为占用
        vehicle.setUpdateTime(new Date());
        vehicleMapper.update(vehicle);
    }

    @Override
    public void back(Long applicationId, Long vehicleId) {
        log.debug("还车业务，参数：{},{}", applicationId, vehicleId);
        Application application = new Application();
        application.setId(applicationId);
        application.setStatus(ApplicationStatusEnum.END.getCode());
        application.setUpdateTime(new Date());
        applicationMapper.update(application);

        //还车需要把车辆状态改为空闲
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setStatus("1");
        vehicle.setUpdateTime(new Date());
        vehicleMapper.update(vehicle);
    }
}
